﻿//
// Created by xqyr on 2025/3/30.
//
#ifndef _WIN32
#include "fclient.h"
#include "log/log.h"
FClient::FClient(const char *name, CBaseWorker *worker)
: CBaseClient(name, worker) {

}

void FClient::onOnline(FdbSessionId_t sid, bool is_first) {
//LOG_INFO("hello worled\n");
    LOG_INFO("onOnline sid=%d, is_first=%d\n", sid, is_first);
    if (is_first) {
        /* add all events to subscribe list */
        CFdbMsgSubscribeList subscribe_list;
//        addNotifyItem(subscribe_list, NTF_ELAPSE_TIME, "my_filter");
//        addNotifyItem(subscribe_list, NTF_ELAPSE_TIME, "raw_buffer");
//        addNotifyItem(subscribe_list, NTF_CJSON_TEST);
//        addNotifyGroup(subscribe_list, MEDIA_GROUP_1);
//        /*
//         * register NTF_MANUAL_UPDATE for manual update: it will not
//         * update unless update() is called
//         */
//        addUpdateItem(subscribe_list, NTF_MANUAL_UPDATE);
        /* subscribe them, leading to onSubscribe() to be called at server */
        subscribe(subscribe_list);
    }
}

void FClient::onOffline(FdbSessionId_t sid, bool is_last) {
    LOG_INFO("onOffline sid=%d, is_last=%d\n", sid, is_last);
}

void FClient::onBroadcast(CBaseJob::Ptr &msg_ref) {
    LOG_INFO("onBroadcast %xd\n",msg_ref.get());
}

void FClient::onReply(CBaseJob::Ptr &msg_ref) {
    LOG_INFO("onReply %xd \n",msg_ref.get());
}

void FClient::onStatus(CBaseJob::Ptr &msg_ref, int32_t error_code, const char *description) {
    auto msg = castToMessage<CBaseMessage *>(msg_ref);
    if (msg->isSubscribe())
    {
        if (msg->isError())
        {
        }
        else
        {
            LOG_INFO("subscribe is ok! sn: %d is received.\n", msg->sn());
        }
    }
    LOG_INFO("Reason: %s\n", description);
}
const char* NAME ="TEST";
#define FDB_CONTEXT CFdbContext::getInstance()
static CBaseWorker main_worker;
void *FClient::start(void *arg) {
#ifdef __WIN32__
    WORD wVersionRequested;
    WSADATA wsaData;
    int err;

/* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
    wVersionRequested = MAKEWORD(2, 2);

    err = WSAStartup(wVersionRequested, &wsaData);
    if (err != 0) {
        /* Tell the user that we could not find a usable */
        /* Winsock DLL.                                  */
        printf("WSAStartup failed with error: %d\n", err);
        return 1;
    }
#endif
    /* start fdbus context thread */
    FDB_CONTEXT->start();
    CBaseWorker *worker_ptr = &main_worker;
    /* start worker thread */
    worker_ptr->start();

    std::string server_name = NAME;
    std::string url(FDB_URL_SVC);
    url += server_name;
    server_name += "_server";
    auto server = new FClient(server_name.c_str(), worker_ptr);
    server->connect(url.c_str());


    /* convert main thread into worker */
    CBaseWorker background_worker;
    background_worker.start(FDB_WORKER_EXE_IN_PLACE);
}

#endif
